package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.Date;
import java.text.SimpleDateFormat;

@Service
public class ScheduledTaskService {

    private final ExecutorService executorService;

    @Autowired
    public ScheduledTaskService(ExecutorService executorService) {
        this.executorService = executorService;
    }

    public void startScheduledTasks() {
        // 任务1：每秒输出当前时间
        executorService.submit(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    System.out.println("当前时间: " + sdf.format(new Date()));
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });

        // 任务2：倒计时1分钟
        executorService.submit(() -> {
            int countdown = 60;
            while (countdown > 0 && !Thread.currentThread().isInterrupted()) {
                try {
                    System.out.println("倒计时: " + countdown + " 秒");
                    countdown--;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            if (countdown == 0) {
                System.out.println("倒计时结束!");
            }
        });
    }

    public void shutdown() {
        executorService.shutdown();
    }
}
